<?php

namespace App\Admin\Actions\Batch;
use Dcat\Admin\Models\Administrator;
use Dcat\Admin\Widgets\Form;
use Dcat\Admin\Traits\LazyWidget;
use Dcat\Admin\Contracts\LazyRenderable;
use App\Models\ProjectUser;
use App\Models\Cabinet;
use App\Models\CabinetAlarm;
use Dcat\Admin\Admin;
use Illuminate\Support\Facades\DB;

class CopyCabinetAlarmAcrossBoxForm extends Form implements LazyRenderable
{
    use LazyWidget;

    // 处理请求
    public function handle(array $input)
    {
        // id转化为数组
        $alarmIds = explode(',', $input['alarmIds'] ?? null);
        $boxId = $input['boxId'] ?? null;
        $box = Cabinet::find($boxId);

        if (! $alarmIds) {
            return $this->response()->error('参数错误');
        }

        $insertData = [];
        foreach ($alarmIds as $alarmId) {
            $one = CabinetAlarm::find($alarmId);
            $oneData['project_id'] = $box['project_id'];
            $oneData['cabinet_pid'] = $boxId;
            $oneData['name'] = $one['name'];
            $oneData['level'] = $one['level'];
            $oneData['condition'] = $one['condition'];
            $oneData['value'] = $one['value'];
            $oneData['active'] = $one['active'];
            $oneData['map_alarm'] = $one['map_alarm'];
            $oneData['created_at'] = date('Y-m-d H:i:s');
            $oneData['updated_at'] = date('Y-m-d H:i:s');
            array_push($insertData, $oneData);
        }
        $res = DB::table('xfy_cabinet_alarms')->insert($insertData);
        if ($res) {
            return $this->response()->success('复制成功')->refresh();
        } else {
            return $this->response()->error('复制失败')->refresh();
        }
    }

    public function form()
    {
        $projectList = ProjectUser::where('user_id',Admin::user()->id)->pluck('projectId');
        
        $boxes = Cabinet::where('pid','0')->whereIn('project_id',$projectList)->pluck('name', 'id')->toArray();

        $this->select('boxId', '复制到')->options($boxes)->required();

        // 设置隐藏表单，传递用户id
        $this->hidden('alarmIds')->attribute('id', 'copy-cabinet-alarm-id');

        $this->confirm('您确定跨盒复制吗？', '');

    }
}